package admin;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import nftrainer.dbconnect.DBConnector;
import nftrainer.dbconnect.interfaces.IDBConnector;

public class Login {
	
	private IDBConnector db = new DBConnector();
	private Connection conn;
	private PreparedStatement stat;
	private ResultSet res;
	
	private boolean isLoggedIn = false;
	
	private final String LOGIN = "SELECT passwort FROM benutzer WHERE name LIKE ?";
	
	public int login(String user, String pw) {
		try {
			this.conn = this.db.getConnection();
			this.stat = this.conn.prepareStatement(LOGIN);
			this.stat.setString(1, user);
			this.res = this.stat.executeQuery();
			if (user == null || "".equals(user) || pw == null || "".equals(pw)) {
				return 0;
			}
			if (this.res.next()) {
				if (this.res.getString(1).equals(this.makeMD5(pw))) {
					this.isLoggedIn = true;
					return 1;
				}
			} else {
				return 0;
			}
		} catch (SQLException e) {
			return -1;
		} catch (NoSuchAlgorithmException e) {
			return -1;
		}
		return 0;
	}
	
	public boolean isLoggedIn() {
		return this.isLoggedIn;
	}
	
	public void logout() {
		this.isLoggedIn = false;
	}
	
	public String makeMD5(String plain) throws NoSuchAlgorithmException {
		MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
		mdAlgorithm.reset();
		mdAlgorithm.update(plain.getBytes());
		
		byte[] digest = mdAlgorithm.digest();
		StringBuffer hexString = new StringBuffer();
		
		for (int i = 0; i < digest.length; i++) {
			plain = Integer.toHexString(0xFF & digest[i]);
			
			if (plain.length() < 2) {
				plain = "0" + plain;
			}
			
			hexString.append(plain);
		}
		
		return hexString.toString().toUpperCase();
	}

}
